package com.baymax.test.scene.demo

import android.os.Bundle
import android.os.SystemClock
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.baymax.lib.key.KeyTransformer
import com.baymax.test.scene.BaseScene
import com.baymax.test.scene.addButton
import com.baymax.test.scene.addDFView
import com.baymax.test.scene.internal.key.KeyCodeCombinationProcessor
import com.baymax.test.scene.internal.key.ViewFinder
import com.baymax.test.scene.internal.key.WatchTvIndicatorImpl
import com.baymax.test.scene.newSceneFlexContainer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class KeyCombineScene : BaseScene() {
    val finder = object : ViewFinder {

        override fun findViewById(id: Int): View =
            this@KeyCombineScene.requireActivity().findViewById(id)

    }
    val transformer: KeyTransformer = object : WatchTvIndicatorImpl(finder) {
        override fun enable(): Boolean {
            return true
        }
    }
    val kc = KeyCodeCombinationProcessor(transformer)
    override fun onCreateView(p0: LayoutInflater, p1: ViewGroup, p2: Bundle?): View {
        return p1.newSceneFlexContainer {

            isFocusable = true
            requestFocus()


            val edit = EditText(requireSceneContext())
            edit.setText("123")
            //123
            //abc
            //12a
            //a1234
            addDFView(300, 100, edit) {

            }
            addButton("send ") {
                sendKey(edit.text.toString())
            }

            addButton("cancel") {
                job.cancel()
            }

        }


    }

    var job: Job = Job()
    fun sendKey(string: String) {
        job.cancel()

        val s = string.map { KeyEvent.keyCodeFromString("KEYCODE_$it") }
        job = launch(Dispatchers.Default) {
            s.forEach {
                delay(300)
                kc.sendKey(newKey(it))
            }
        }
    }

    fun newKey(code: Int): KeyEvent {
        return KeyEvent(
            SystemClock.uptimeMillis().toLong(),
            SystemClock.uptimeMillis().toLong(),
            KeyEvent.ACTION_DOWN,
            code,
            0
        )
    }


}
